package seeders

import (
	"goravel/app/models"

	"github.com/goravel/framework/facades"
)

type RolePermissionSeeder struct {
}

// Signature The name and signature of the seeder.
func (s *RolePermissionSeeder) Signature() string {
	return "RolePermissionSeeder"
}

// Run executes the seeder logic.
func (s *RolePermissionSeeder) Run() error {
	// 获取超级管理员角色
	var adminRole models.Role
	if err := facades.Orm().Query().Where("role_name", "超级管理员").First(&adminRole); err != nil {
		facades.Log().Error("Failed to find admin role: ", err)
		return err
	}

	// 获取所有权限
	var permissions []models.Permission
	if err := facades.Orm().Query().Find(&permissions); err != nil {
		facades.Log().Error("Failed to find permissions: ", err)
		return err
	}

	// 为超级管理员分配所有权限
	for _, permission := range permissions {
		var exists bool
		if err := facades.Orm().Query().Model(&models.RolePermission{}).
			Where("role_id", adminRole.ID).
			Where("permission_id", permission.ID).
			Exists(&exists); err != nil {
			facades.Log().Error("Failed to check role permission existence: ", err)
			return err
		}

		if !exists {
			rolePermission := models.RolePermission{
				RoleId:       adminRole.ID,
				PermissionId: permission.ID,
			}

			if err := facades.Orm().Query().Create(&rolePermission); err != nil {
				facades.Log().Error("Failed to create role permission: ", err)
				return err
			}
		}
	}

	return nil
}
